package com.wwg.warehouse.utils

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlin.coroutines.Continuation
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.startCoroutine

const val START = 0
const val COMPLETE = 1
const val ERROR = -1

fun <R, T> launchCoroutineOnIO(receiver: R, block: suspend R.() -> T) {
    block.startCoroutine(receiver, object : Continuation<T> {
        override fun resumeWith(result: Result<T>) {
            println("Coroutine end: $result")
        }

        override val context: CoroutineContext
            get() = Dispatchers.IO
    })
}

class ProducerScope<T> {
    suspend fun produce(value: T) {
        withContext(Dispatchers.Main) {
            println("coroutine state: $value")
        }
    }
}

fun <T> launchCoroutineOnIO(block: suspend ProducerScope<Int>.() -> T) {
    launchCoroutineOnIO(ProducerScope<Int>()) {
        try {
            produce(START)
            block(this)
            produce(COMPLETE)
        } catch (t: Throwable) {
            produce(ERROR)
            t.printStackTrace()
        }
    }
}